import { initParticlesJS } from '../particles.js';

// 粒子效果
initParticlesJS();

// 页面加载后初始化板块内容
document.addEventListener('DOMContentLoaded', async function() {
    // 隐藏主视图，显示板块内容视图
    document.getElementById('mainView').classList.add('hidden');
    document.getElementById('forumContentView').classList.remove('hidden');
    
    // 返回按钮点击事件（关键修改）
    document.getElementById('backToForums').addEventListener('click', function() {
        // 替换原有alert，直接跳转到forum.html
        window.location.href = 'forum.html';
    });

    // 发新帖按钮点击事件
    document.getElementById('createPostBtn').addEventListener('click', function() {
        window.location.href = 'putPost.html';  // 跳转到发布新帖页面
    });

    // 从 URL 中获取板块 ID
    const urlParams = new URLSearchParams(window.location.search);
    const plateId = urlParams.get('section');
    console.log(plateId);

    if (plateId) {
        try {
            // 根据板块 ID 获取板块详细信息
            const plateResponse = await fetch(`http://localhost:3000/api/getPlateById?id=${plateId}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include'  // 包含凭证（如Cookie）
            });

            if (!plateResponse.ok) {
                throw new Error('网络请求失败');
            }

            const plateResponseData = await plateResponse.json();
            const plateInfo = plateResponseData.data;

            // 将板块信息填充到页面中
            document.getElementById('currentForumName').textContent = plateInfo.plateName;
            document.getElementById('forumTitle').textContent = plateInfo.plateName;
            document.getElementById('forumDescription').textContent = plateInfo.plateDescription;

            // 根据板块 ID 获取对应板块下的所有帖子
            const postsResponse = await fetch(`http://localhost:3000/api/getPostsByPlateId?plateId=${plateId}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include'  // 包含凭证（如Cookie）
            });

            if (!postsResponse.ok) {
                throw new Error('网络请求失败');
            }

            const postsResponseData = await postsResponse.json();
            const posts = postsResponseData.data;
            // 打印每个帖子的postId
            posts.forEach(post => {
                console.log("postId为：", post.postId);
            });
            

            // 生成主题列表
            const topicsListElement = document.getElementById('topicsList');
            const topicsHTML = posts.map(post => `
                <div class="topic-item border-b border-gray-100 last:border-0">
                    <div class="p-5 flex flex-col md:flex-row md:items-center">
                        <div class="flex-1 flex items-start mb-3 md:mb-0">
                            <img src="${post.user && post.user.avatar ? post.user.avatar : '/assets/avatar/defaultAvatar.png' }" alt="${post.user.nickname}" class="w-10 h-10 rounded-full mr-4">
                            <div class="flex-1">
                                <div class="mb-1 flex items-center">
                                    <!-- 修改关键：添加指向post.html的链接，传递帖子ID -->
                                    <a href="post.html?id=${post.postId}&plateId=${plateId}" class="text-lg font-medium text-gray-900 hover:text-blue-600 transition-colors">${post.title}</a>
                                    <!-- 这里可以根据帖子的热度等条件添加徽章 -->
                                </div>
                                <div class="text-sm text-gray-500">
                                    <span class="mr-3">${post.user.nickname}</span>
                                    <span class="mr-3"><i class="far fa-clock mr-1"></i>${post.createTime}</span>
                                </div>
                            </div>
                        </div>
                        <div class="flex items-center space-x-6">
                            <div class="text-center">
                                <div class="text-xl font-medium text-gray-700">${post.commentCount}</div>
                                <div class="text-xs text-gray-500">回复</div>
                            </div>
                            <div class="text-center">
                                <div class="text-xl font-medium text-gray-700">${post.viewCount || 0}</div>
                                <div class="text-xs text-gray-500">浏览</div>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');

            topicsListElement.innerHTML = topicsHTML;
        } catch (error) {
            console.error('获取板块信息或帖子信息失败:', error);
        }
    }
});